package com.cloud.pole.common.interceptor;

import com.cloud.pole.common.constant.CommonConstants;
import com.cloud.pole.common.context.BaseContextHandler;
import com.cloud.pole.common.exception.auth.UserTokenException;
import com.cloud.pole.common.util.jwt.IJWTInfo;
import com.cloud.pole.common.util.jwt.JWTInfo;
import com.cloud.pole.common.util.jwt.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by ace on 2017/9/12.
 */
@SuppressWarnings("ALL")
public class ServiceAuthRestInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(ServiceAuthRestInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        String token = request.getHeader(CommonConstants.AUTH_CLIENT_TOKEN_HEADER);
        logger.info("token[" + token + "] requestURI [" + request.getRequestURI() + "]");

        if(StringUtils.isEmpty(token)) {
            logger.error("token[" + token + "] requestURI [" + request.getRequestURI() + "] token is null!");
         	throw new UserTokenException("client token is null!");
        }
        IJWTInfo infoFromToken = JwtTokenUtil.getInfoFromToken(token);
//      logger.debug("getType[" + infoFromToken.getType() + "] USER_TYPE_CLINET [" + JWTInfo.USER_TYPE_CLINET + "]");
//      logger.debug("getId[" + infoFromToken.getId() + "] CLIENT_USER_USER_ID [" + CommonConstants.CLIENT_USER_USER_ID + "]");
//      logger.debug("getUniqueName[" + infoFromToken.getUniqueName() + "] CLIENT_USER_NAME [" + CommonConstants.CLIENT_USER_NAME + "]");
//      logger.debug("getNickName[" + infoFromToken.getNickName() + "] CLIENT_NICK_NAME [" + CommonConstants.CLIENT_NICK_NAME + "]");
        if(infoFromToken.getType() != JWTInfo.USER_TYPE_CLINET || 
           !StringUtils.equals(infoFromToken.getId(), CommonConstants.CLIENT_USER_USER_ID)|| 
           !StringUtils.equals(infoFromToken.getUniqueName(), CommonConstants.CLIENT_USER_NAME)|| 
           !StringUtils.equals(infoFromToken.getNickName(), CommonConstants.CLIENT_NICK_NAME)) {
           logger.error("token[" + token + "] requestURI [" + request.getRequestURI() + "] token is forbid!");
        	throw new UserTokenException("token is forbid!");
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
